package com.newtype.meeting.client.mvc;

import java.util.HashMap;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.newtype.meeting.client.AppEvents;
import com.newtype.meeting.client.GMeeting;
import com.newtype.meeting.client.model.Account;
import com.newtype.meeting.client.service.AccountServiceAsync;
import com.newtype.meeting.client.service.LoginServiceAsync;
import com.newtype.meeting.shared.LoginInfo;

public class AppController extends Controller {
	private AppView appView;
	private AccountServiceAsync accountService;
	private LoginServiceAsync loginService;

	@Override
	protected void initialize() {
		appView = new AppView(this);
	}

	public AppController() {
		accountService = Registry.get(GMeeting.ACCOUNT_SERVICE);
		loginService = Registry.get(GMeeting.LOGIN_SERVICE);
		registerEventTypes(AppEvents.Init, AppEvents.Login, AppEvents.Error,
				AppEvents.CheckLogin);
	}

	@Override
	public void handleEvent(AppEvent event) {
		EventType type = event.getType();
		if (type == AppEvents.Init) {
			forwardToView(event);
		} else if (type == AppEvents.Login) {
			onToLogin(event);
		} else if (type == AppEvents.Error) {
			onError(event);
		} else if (type == AppEvents.CheckLogin) {
			onCheckLogin(event);
		} else if (type == AppEvents.ToGoogleRegister) {
			forwardToView(event);
		}
	}

	public void onToLogin(final AppEvent event) {
		final AppEvent ae = new AppEvent(event.getType());
		loginService.googleLogin(GWT.getHostPageBaseURL(),
				new AsyncCallback<LoginInfo>() {
					@Override
					public void onFailure(Throwable caught) {
						Dispatcher.forwardEvent(AppEvents.Error);
					}

					@Override
					public void onSuccess(LoginInfo result) {
						final LoginInfo loginInfo=result;
						//判断是否登录
						if(loginInfo.isLoggedIn()){
							//判断邮箱是否存在
							//1.如果存在，获取该邮箱用户的信息
							//2.如果不存在，继续注册
							loginService.isEmailExist(loginInfo.getEmailAddress(), new AsyncCallback<Boolean>(){
								@Override
								public void onFailure(Throwable caught) {
									Dispatcher.forwardEvent(AppEvents.Error);
								}
								@Override
								public void onSuccess(Boolean result) {
									System.out.println("邮箱是否存在："+result);
									if(result){
										accountService.getAccountByEmail(loginInfo.getEmailAddress(), new AsyncCallback<Account>(){
											@Override
											public void onFailure(
													Throwable caught) {
												Dispatcher.forwardEvent(AppEvents.Error);
											}
											@Override
											public void onSuccess(Account result) {
												Registry.register(GMeeting.LOGININFO, loginInfo);
												validationLogin(result);
											}
										});
									//判断是否是管理员
									}else{
										if(loginInfo.isAdmin()){
											MessageBox.alert("提示", "管理员初始化程序"+"<a href='"+loginInfo.getLogoutUrl()+"'>退出</a>", null);
										}else{
											//继续注册
											Registry.register(GMeeting.LOGININFO, loginInfo);
											forwardToView(new AppEvent(
													AppEvents.ToGoogleRegister, loginInfo));
										}
									}
								}
							});							
						}else{
							Registry.register(GMeeting.LOGININFO, loginInfo);
							forwardToView(ae);
						}
					}
				});
	}

	private void onCheckLogin(AppEvent event) {
		HashMap<String, String> data = event.getData();

		accountService.checkLogin(data, new AsyncCallback<Account>() {
			@Override
			public void onFailure(Throwable caught) {
				Dispatcher.forwardEvent(AppEvents.Error);
			}

			@Override
			public void onSuccess(Account result) {
				validationLogin(result);
			}
		});
	}
	
	/**
	 * 功能：验证用户登录信息
	 * @param account
	 */
	public void validationLogin(Account account){
		System.out.println("调用alidationLogin方法");
		if (account != null && account.getStatus().equals("1")) {
			Registry.register(GMeeting.ACCOUNT, account);
			forwardToView(new AppEvent(AppEvents.LoginHide));
		} else if (account != null && account.getStatus().equals("0")) {
			MessageBox.alert("提示信息", "帐号尚未开通！", null);
			forwardToView(new AppEvent(AppEvents.LoginReset));
		} else if (account != null && account.getStatus().equals("2")) {
			MessageBox.alert("提示信息", "帐号已停用！", null);
			forwardToView(new AppEvent(AppEvents.LoginReset));
		} else {
			MessageBox.alert("提示信息", "帐号密码有误，请重新登入！", null);
			forwardToView(new AppEvent(AppEvents.LoginReset));
		}
	}

	private void onError(AppEvent event) {
		System.out.println("Error: " + event.<Object> getData());
	}

	private void forwardToView(AppEvent event) {
		forwardToView(appView, event);
	}

}
